<script setup>
import { ref, onMounted,computed,nextTick } from 'vue'
import {
  ElTable,
  ElTableColumn,
  ElMessage,
  ElDialog,
  ElForm,
  ElFormItem,
  ElInput,
  ElButton,
  ElDatePicker,
  ElTreeSelect
} from 'element-plus'
import {getReturnList, deptList, getLocationTree, addReturn, getReturnDetail} from '@/api/AssetReturn'

import {Search, Refresh, Plus, View} from '@element-plus/icons-vue'

// 表格数据
const returnList = ref([])

// 搜索条件
const queryForm = ref({
  id: '',
  useStatus: "2"
})

// 获取资产归还信息列表
const fetchReturnList = () => {
  getReturnList(queryForm.value).then(res => {
    if (res.code === 200) {
      returnList.value = res.data
    }
  })
}

// 根据资产名称查询归还列表
const handleReturnSearch = () => {
  if (!queryForm.value.id) {
    ElMessage.warning('请输入资产id');
    return;
  }
  const params = {
    id: queryForm.value.id,
    useStatus: "2"
  }

  getReturnList(params).then(res => {
    if (res.code === 200) {
      returnList.value = res.data
    }
  })

}

// 重置资产归还列表数据
const handleReturnReset = () => {
  queryForm.value.id = ''
  fetchReturnList()
}


// 弹窗状态
const formVisible = ref(false)
// 弹窗标题
const dialogTitle = ref('')

// 重置表单
const resetForm = () => {
  form.value = {
    useStatus: "2",
    actualReturn: new Date().toISOString().split('T')[0],
    deptId: '',
    locationId: "",
    usagePurpose: '',
    assets: []
  }
}

// 新增资产归还数据
const addReturnData = () => {
  // 重置表单 修改编辑状态
  resetForm()
  dialogTitle.value = '新增资产归还'
  // 弹框显示
  formVisible.value = true
}


const form = ref({
  useStatus: "2",
  actualReturn: new Date().toISOString().split('T')[0],
  deptId: '',
  locationId: "",
  usagePurpose: '',
  assets: []
})


// 资产所在部门列表数据
const assetDept=ref([]);

// 获取资产所在部门树形结构
const getAssetDeptList = () => {
  deptList().then(res => {
    if (res.code === 200) {
      console.log(res.data,7877)
      assetDept.value = res.data
    }
  })
}

// 借用后资产位置树形数据
const parentLocations = ref([])

// 获取位置树形结构
const getLocationTreeData = () => {
  getLocationTree().then(res => {
    if (res.code === 200) {
      parentLocations.value = res.data
    }
  })
}


// 表单验证规则
const rules = {
  actualReturn: [
    { required: true, message: '请选择归还日期', trigger: 'change' }
  ],
  deptId: [
    { required: true, message: '请选择归还后使用部门', trigger: 'change' }
  ],
  locationId: [
    { required: true, message: '请选择归还后位置', trigger: 'change' }
  ],
  usagePurpose: [
    { max: 200, message: '备注长度不能超过200个字符', trigger: 'blur' }
  ]
}


// 资产归还表单实例对象
const formRef = ref(null)

// 提交表单
const handleSubmit = () => {

  if(!form.value.assets.length > 0) return ElMessage.error('请选择资产')
  formRef.value.validate(async (vaild) =>{
    if (vaild) {
      addReturn(form.value).then(res => {
        if (res.code === 200) {
          ElMessage.success(`归还成功`)
          formVisible.value = false
          resetForm()
          fetchReturnList()
        }
      })
    }
  })
}


// 定义子组件 ref
const assetsListRef = ref(null)

// 点击取消关闭弹框
const handleCancel = () => {
  formVisible.value = false
  // 调用子组件的取消选中方法
  assetsListRef.value?.clearSelection()
}

// 获取子组件选择借用的资产
const handleAssetSelect = (assetList) =>{
  form.value.assets = assetList
  console.log(assetList,6666)
}


// 控制 Drawer 显示状态
const drawerVisible = ref(false)
// 点击编号时触发的方法
const handleClickTag = (id) => {
  console.log(id)
  
  getReturnDetail({id}).then(res => {
    if (res.code === 200) {
      console.log(res,"详情数据")
      nextTick(() => {
        showFormData.value.id = res.data.id
        showFormData.value.createTime = res.data.createTime
        showFormData.value.username = res.data.username
        showFormData.value.deptName = res.data.deptName
        showFormData.value.expectedReturn = res.data.expectedReturn
        showFormData.value.locationName = res.data.locationName
        showFormData.value.usagePurpose = res.data.usagePurpose
        tableData.value = res.data.assets
        console.log(formDataValues.value,8888)
      })
    }
  })
  drawerVisible.value = true
}

const showFormData = ref({
  id: '',
  createTime: '',
  // username: '',
  deptName: '',
  locationName: '',
  usagePurpose: ''
})

const formDataValues = computed(()=>[


  {
    label: '当前部门',
    value: showFormData.value.deptName
  },
  {
    label: '归还人员',
    value: showFormData.value.username
  },
  {
    label: '当前位置',
    value: showFormData.value.locationName
  },
    {
    label: '备注',
    value: showFormData.value.usagePurpose
    },
  {
    label: '创建时间',
    value: showFormData.value.createTime
  },
])

// tableData
const tableColumns = ref([
  {prop: 'name', label: '资产名称'},
  { prop: 'categoryName', label: '资产分类' },
  { prop: 'assetCode', label: '资产编码' },
  { prop: 'model', label: '型号规格' },
  // { prop: 'status', label: '状态' },
  // { prop: 'serialNumber', label: '序列号' },
  { prop: 'locationName', label: '位置' }
])

const tableData = ref([])

// 关闭 Drawer 的方法
const closeDrawer = () => {
  drawerVisible.value = false
}

onMounted(() => {
  fetchReturnList()
  //获取位置树数据
  getLocationTreeData()
  //获取部门树数据
  getAssetDeptList()
})
</script>

<template>
  <!-- 新增资产归还按钮与按资产名称搜索资产归还列表 -->

  <!-- 搜索框 -->
  <el-form :inline="true" :model="queryForm" style="margin: 10px 0 0 0;">
    <el-form-item>
      <el-space>
        <el-input v-model="queryForm.id" placeholder="请输入资产ID" clearable style="width: 300px"
                  :prefix-icon="Search">
          <template #append>
            <el-button type="primary" style="background: #409eff;color: #ffffff;" :icon="Search"
                       @click="handleReturnSearch">搜索
            </el-button>
          </template>
        </el-input>
        <el-button type="primary" plain :icon="Refresh" @click="handleReturnReset">重置</el-button>
        <el-button plain type="primary" :icon="Plus" @click="addReturnData">新增
        </el-button>
      </el-space>
    </el-form-item>
  </el-form>


  <!---------- 资产归还弹窗 ------------>
  <el-dialog v-model="formVisible" @close="handleCancel" close-on-click-modal="false" :title="dialogTitle" width="71%">
    <el-form :model="form" :rules="rules" label-width="130px" ref="formRef" inline>
      <el-form-item label="归还日期" prop="actualReturn">
        <el-date-picker
          v-model="form.actualReturn"
          type="date"
          clearable
          placeholder="选择归还日期"
          value-format="YYYY-MM-DD"
        />
      </el-form-item>

      <el-form-item label="归还后使用部门" prop="deptId">
        <el-tree-select
          v-model="form.deptId"
          placeholder="请选择归还后使用部门"
          :data="assetDept"
          node-key="id"
          clearable
          :props="{label:'deptName',children:'children'}"
          check-strictly
          :render-after-expand="false"
          style="width: 200px"
        />
      </el-form-item>

      <el-form-item label="归还后位置" prop="locationId">
        <el-tree-select
          v-model="form.locationId"
          placeholder="请选择上级位置"
          :data="parentLocations"
          node-key="id"
          clearable
          :props="{label:'locationName',children:'children'}"
          check-strictly
          :render-after-expand="false"
          style="width: 200px"
        />
      </el-form-item>
      
      <el-form-item label="备注" prop="usagePurpose" class="full-width">
        <el-input
          v-model="form.usagePurpose"
          type="textarea"
          :rows="3"
          placeholder="请输入备注内容"
          maxlength="200"
          show-word-limit
        />
      </el-form-item>
    </el-form>

    <!-- 已借出的资产列表 -->
    <!-- 资产列表 -->
    <AssetsList :status="2" ref="assetsListRef" @assetSelect="handleAssetSelect"/>

    <template #footer>
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" @click="handleSubmit">确定</el-button>
    </template>
  </el-dialog>

  <!----------- 资产归还列表 ----------->
  <el-table
    :data="returnList"
    height="80%"
    style="margin-top: 10px;cursor:pointer;"
    >
    <!--    <el-table-column prop="username" label="归还人" align="center"/>-->
    <!-- <el-table-column prop="createTime" label="创建日期" align="center" /> -->
    <el-table-column prop="dept_name" label="现属部门" align="left"/>
    <el-table-column prop="location_name" label="现属位置" align="center"/>
    <el-table-column prop="createTime" label="归还日期" align="center"/>
    <el-table-column prop="id" label="操作" align="center" width="150">
      <template #default="scope">
        <el-link type="primary" plain :icon="View" @click="handleClickTag(scope.row.id)">查看</el-link>
      </template>
    </el-table-column>
    <!--    <el-table-column prop="usage_purpose" label="备注" align="center">-->
    <!--      <template #default="scope">-->
    <!--        <el-tooltip :content="scope.row.usage_purpose" placement="top" :disabled="!scope.row.usage_purpose || scope.row.usage_purpose.length <= 10">-->
    <!--          <span class="table-cell-truncate">{{ scope.row.usage_purpose }}</span>-->
    <!--        </el-tooltip>-->
    <!--      </template>-->
    <!--    </el-table-column>-->
  </el-table>



  <Drawer v-model:visible="drawerVisible" :formData="showFormData" :formDataValues="formDataValues" :tableColumns="tableColumns" :tableData="tableData" @close="closeDrawer" />

</template>

<style scoped lang="less">
.mb-4 {
  margin-bottom: 1rem;
}
.full-width {
  width: 100%;
  
  .el-textarea {
    width: 97%;
  }
}
.table-cell-truncate {
  display: inline-block;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 200px; /* 根据实际情况调整 */
}
</style>